package com.kanshu.ksgb.fastread.doudou.common.util;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.util.Log;

import java.util.List;

/**
 * Title:
 * Description:
 * Copyright: Copyright(c)2018
 * Company: 看书网
 * CreateTime: 2018/5/30 9:38
 *
 * @author EvanHe
 * @version 3.0
 */
public class LocationUtils {
    private static final String TAG = "LocationUtils";

    public static Location getLocation(Context context) {
        //1.获取位置管理器
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        //2.获取位置提供器，GPS或是NetWork
        String locationProvider;
        try {
            assert locationManager != null;
            List<String> providers = locationManager.getProviders(true);
            if (Utils.isEmptyList(providers)) {
                return null;
            }
            if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
                Log.d(TAG, "网络定位");
                locationProvider = LocationManager.NETWORK_PROVIDER;
            } else if (providers.contains(LocationManager.GPS_PROVIDER)) {
                Log.d(TAG, "GPS定位");
                locationProvider = LocationManager.GPS_PROVIDER;
            } else {
                Log.d(TAG, "没有可用的位置提供器");
                return null;
            }
        }catch (Exception e){
            e.printStackTrace();
            Log.d(TAG, "没有可用的位置提供器");
            return null;
        }
        // 需要检查权限,否则编译报错,想抽取成方法都不行,还是会报错。只能这样重复 code 了。
        if (Build.VERSION.SDK_INT >= 23 &&
                ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return null;
        }
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return null;
        }
        //3.获取上次的位置，一般第一次运行，此值为null
        // 监视地理位置变化，第二个和第三个参数分别为更新的最短时间minTime和最短距离minDistace
        //locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener);
        try {
            return locationManager.getLastKnownLocation(locationProvider);
        } catch (Exception e) {
            return null;
        }
    }

}
